package com.oktest.measure.kt

import android.content.Context
import android.os.Environment
import android.text.Editable
import android.text.TextWatcher
import android.util.DisplayMetrics
import android.view.WindowManager
import android.widget.EditText
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import io.reactivex.subjects.PublishSubject
import java.util.concurrent.TimeUnit

/**
 * @Author hhh
 * @Date 2020/10/23
 */

const val NOTICE_ID = "notice_detail_id"
const val TASK_ID = "task_detail_id"
const val TASK_COMPLETED = "已完成"
const val TASK_DEFAULT_ID = 0L

const val API_SUCCESS_CODE = 1000
const val WORK_HTTP_TIMEOUT = 60 // 工作页超时60秒

const val EVENT_XML_DOWNLOAD = "event_xml_download"
const val EVENT_HOME_TASK_REFRESH = "event_home_task_refresh"   //
const val EVENT_HOME_TASK_GET = "event_home_task_get"

// EditText文本变化监听
fun EditText.afterTextChange(timeout: Long = 1000, block: (String?) -> Unit): Disposable {
    val publish = PublishSubject.create<String>()
    this.addTextChangedListener(object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

        }

        override fun afterTextChanged(s: Editable?) {
            val text = s?.toString() ?: ""
            publish.onNext(text)
        }
    })
    // timeout ms之内只会返回一个变化值
    // distinctUntilChanged 过滤掉连续重复的元素
    // distinct 过滤掉重复的元素
    return publish.distinctUntilChanged()
        .debounce(timeout, TimeUnit.MILLISECONDS)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe {
            block(it)
        }
}

fun Context.screenWidth() :Int{
    val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
    val defaultDisplay = windowManager.defaultDisplay
    val displayMetrics = DisplayMetrics()
    defaultDisplay.getMetrics(displayMetrics)
    return displayMetrics.widthPixels
}

fun Context.screenHeight() :Int{
    val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
    val defaultDisplay = windowManager.defaultDisplay
    val displayMetrics = DisplayMetrics()
    defaultDisplay.getMetrics(displayMetrics)
    return displayMetrics.heightPixels
}
